<?php

namespace app\admin\controller\flow;

use app\common\controller\FlowBackend;
use app\common\library\FlowEngine;
use think\Db;
use app\admin\model\Admin;
use app\common\library\Word;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Cooperation extends FlowBackend
{
    
    /**
     * Cooperation模型对象
     * @var \app\admin\model\flow\Cooperation
     */
    protected $model = null;
    protected $noNeedRight=['*'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\flow\Cooperation;
        $this->flow = new FlowEngine('Cooperation');
        $this->departmentList = $this->model->allDepartmentName();
        $this->view->assign("departmentList", $this->departmentList);
        $this->view->assign("typeList", $this->model->getTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 直接提交流程
     */
    public function add()
    {
        $params = $this->request->post("row/a");
        $flowTmp = $this->scheme->get($this->request->request("ids"));
        if ($this->request->isPost()) {
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $this->model->validate($validate);
                }
                $params['participating_departments'] = implode(',',$params['participating_departments']);
                $this->flow->start($params);
                $this->success();
            }
            catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            }
            catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $serial_no = $this->getnumber($flowTmp['flowcode']);
        $content = [];
        if(isset($flowTmp->flowcontent)) {
            $content = json_decode($flowTmp->flowcontent, true);
        }
        else {
            $this->error(__('流程代码不存在'));
        }
        $lines = $content['lines'];
        //所有节点信息
        $nodes = $content['nodes'];
        $rtn = array_search('start', array_column($nodes, 'type'));
        $this->currentNode = $nodes[$rtn];
        $fieldList = $this->getNodeField($this->request->request("ids"),$this->currentNode['id'],$flowTmp['bizscheme']);
        $this->view->assign("serial_no", $serial_no);
        $this->assignconfig('flowCode', $flowTmp['flowcode']);
        $this->view->assign('fieldList', $fieldList);
        //$this->view->assign('unit_id', implode(',',$this->auth_unit_ids));
        return $this->view->fetch();
    }

    /**
     * 寻找下一个审批节点,同意按钮执行的方法
     */
    public function edit($ids = NULL)
    {
        $ids = $this->request->request('ids');
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $taskid = $this->request->request('taskid');
        $task = null;
        $mode = $this->request->request('mode');
        if ($mode == 'view') {
            $task = $this->task->where(['id' => $taskid])->find();
        }
        else {
            $task = $this->task->where(['id' => $taskid])->where('status', 0)->find();
        }
        if (!$task)
            $this->error(__('找不到当前任务'));
        $schme = $this->scheme->get($task['flowid']);
        $instance = $this->instance->get($task['instanceid']);
        $originator = $this->adminModel->get($instance['originator']);
        $fieldList = $this->getNodeField($task["flowid"], $task['stepid'], $schme['bizscheme'], $mode);
        if ($this->request->isPost()) {
            $comment = $this->request->post('comment') == '' ? '' : $this->request->post('comment');
            $cfile = $this->request->post('cfile') == '' ? '' : $this->request->post('cfile');
            $data = $this->request->request("row/a");
            $data['id'] = $ids;
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $this->model->validate($validate);
                }
                $writeList = null;
                foreach ($fieldList as $key => $j) {
                    if ($j['write'] == 1 && isset($data[$key])) {
                        $writeList[$key] = $data[$key];
                    }
                }
				//职能部门
                if ($writeList) {
                    if(isset($writeList['divisions'])) {
                        $writeList['divisions'] = implode(',',$writeList['divisions']);
                    }
                    Db::table($schme['bizscheme'])->where(['id' => $data['id']])->update($writeList);
                }
                $this->flow->next($taskid, $data, '', $comment,$cfile);
                $this->success();
            }
            catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            }
            catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $history = Db::table($this->prefix . 'flow_task')
            ->alias('main')
            ->join($this->prefix . 'admin admin', 'admin.id=main.receiveid', 'LEFT')
            ->where(['instanceid' => $task['instanceid'], 'main.status' => 2])
            ->where('main.deletetime','null')
            ->field(["main.receiveid", "main.stepname", "main.comment","main.cfile", "admin.nickname", "main.completedtime"])
            ->order('main.createtime asc,main.completedtime asc')
            ->select();

        //字段权限
        $this->assignconfig('task', $task);
        $this->assignconfig('flowCode', $schme['flowcode']);
        $this->view->assign("history", $history);
        $this->view->assign("mode", $mode);
        $this->view->assign("instance", $instance);
        $this->view->assign("row", $row);
        $this->view->assign("originator", $originator);
        $this->view->assign("auth", $this->auth);
        $this->view->assign('fieldList', $fieldList);
        $this->view->assign('task', $task);
        $this->view->assign('scheme', $schme);
        $this->view->assign('participatingList', build_select('row[participating_departments][]',$this->departmentList, $row['participating_departments'], ['class' => 'form-control selectpicker','multiple'=>'']));
        $this->view->assign('divisionsList', build_select('row[divisions][]',$this->departmentList, $row['divisions'], ['class' => 'form-control selectpicker','multiple'=>'','data-rule'=>'required']));
      
		return $this->view->fetch();
    }

    /**
     * 寻找下一个审批节点,同意按钮执行的方法
     */
    public function compile($ids = NULL)
    {
        $ids = $this->request->request('ids');
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $taskid = $this->request->request('taskid');
        $task = null;
        $mode = $this->request->request('mode');
        if ($mode == 'view') {
            $task = $this->task->where(['id' => $taskid])->find();
        }
        else {
            $task = $this->task->where(['id' => $taskid])->where('status', 0)->find();
        }
        if (!$task)
            $this->error(__('找不到当前任务'));
        $schme = $this->scheme->get($task['flowid']);
        $instance = $this->instance->get($task['instanceid']);
        $originator = $this->adminModel->get($instance['originator']);
        $fieldList = $this->getNodeField($task["flowid"], $task['stepid'], $schme['bizscheme'], $mode);
        if ($this->request->isPost()) {
            $comment = $this->request->post('comment') == '' ? '' : $this->request->post('comment');
            $cfile = $this->request->post('cfile') == '' ? '' : $this->request->post('cfile');
            $data = $this->request->request("row/a");
            $data['id'] = $ids;
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $this->model->validate($validate);
                }
                $writeList = null;
                foreach ($fieldList as $key => $j) {
                    if ($j['write'] == 1 && isset($data[$key])) {
                        $writeList[$key] = $data[$key];
                    }
                }
                //职能部门
                if ($writeList) {
                    if(isset($writeList['divisions'])) {
                        $writeList['divisions'] = implode(',',$writeList['divisions']);
                    }
                    Db::table($schme['bizscheme'])->where(['id' => $data['id']])->update($writeList);
                }
                $this->flow->next($taskid, $data, '', $comment,$cfile);
                $this->success();
            }
            catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            }
            catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $history = Db::table($this->prefix . 'flow_task')
            ->alias('main')
            ->join($this->prefix . 'admin admin', 'admin.id=main.receiveid', 'LEFT')
            ->where(['instanceid' => $task['instanceid'], 'main.status' => 2])
            ->where('main.deletetime','null')
            ->field(["main.receiveid", "main.stepname", "main.comment","main.cfile", "admin.nickname", "main.completedtime"])
            ->order('main.createtime asc,main.completedtime asc')
            ->select();

        //字段权限
        $this->assignconfig('task', $task);
        $this->assignconfig('flowCode', $schme['flowcode']);
        $this->view->assign("history", $history);
        $this->view->assign("mode", $mode);
        $this->view->assign("instance", $instance);
        $this->view->assign("row", $row);
        $this->view->assign("originator", $originator);
        $this->view->assign("auth", $this->auth);
        $this->view->assign('fieldList', $fieldList);
        $this->view->assign('task', $task);
        $this->view->assign('scheme', $schme);
        $this->view->assign('participatingList', build_select('row[participating_departments][]',$this->departmentList, $row['participating_departments'], ['class' => 'form-control selectpicker','multiple'=>'']));
        $this->view->assign('divisionsList', build_select('row[divisions][]',$this->departmentList, $row['divisions'], ['class' => 'form-control selectpicker','multiple'=>'']));

        return $this->view->fetch();
    }

    /**
     * 寻找下一个审批节点,同意按钮执行的方法
     */
    public function show($ids = NULL)
    {
        $ids = $this->request->request('ids');
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $instanceid = $this->request->request('instanceid');
        $mode = $this->request->request('mode');
        $instance = $this->instance->get($instanceid);
        $schme = $this->scheme->get($instance->scheme);
        $originator = $this->adminModel->get($instance['originator']);

        $history = Db::table($this->prefix . 'flow_task')
            ->alias('main')
            ->join($this->prefix . 'admin admin', 'admin.id=main.receiveid', 'LEFT')
            ->where(['instanceid' => $instanceid, 'main.status' => 2])
            ->where('main.deletetime','null')
            ->field(["main.receiveid", "main.stepname", "main.comment","main.cfile", "admin.nickname", "main.completedtime"])
            ->order('main.createtime asc,main.completedtime asc')
            ->select();

        $lastTask = Db::name('flow_task')->where(['instanceid' => $instanceid])->order('createtime desc')->find();
        $this->assignConfig('lastTask', $lastTask);

        //字段权限
        //$this->assignconfig('task', $task);
        $this->assignconfig('flowCode', $schme['flowcode']);
        $this->view->assign("history", $history);
        $this->view->assign("mode", $mode);
        $this->view->assign("instance", $instance);
        $this->view->assign("row", $row);
        $this->view->assign("originator", $originator);
        $this->view->assign("auth", $this->auth);
        //$this->view->assign('fieldList', $fieldList);
        //$this->view->assign('task', $task);
        $this->view->assign('scheme', $schme);
        $this->view->assign('participatingList', build_select('row[participating_departments][]',$this->departmentList, $row['participating_departments'], ['class' => 'form-control selectpicker','multiple'=>'','disabled'=>'true',]));
        return $this->view->fetch();
    }

    public function previewWord()
    {
        $ids = $this->request->request('ids');
        $instanceid = $this->request->request('instanceid');

        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $instance = $this->instance->get($instanceid);
        $admin = Admin::get($instance['originator']);
        $units = Db::name('department')
            ->alias('a')
            ->join('units b', 'b.id = a.unit_id', 'LEFT')
            ->where(['a.id' => $admin['department_id']])
            ->field('b.name')
            ->find();

        $assetsIds = explode(',', $row['assets_ids']);
        $data = Db::name('assets')
            ->where(['id' => ['in', $assetsIds]])
            ->field('id,assets_name,unit,assets_type,price,assets_sn,quantity,net_value')
            ->select();

        $sealTasks = Db::name('flow_task')->where([
            'instanceid' => $instanceid,
            'is_hide' => 0,
            'status' => 2,
            'seal_id' => ['<>',0]
        ])->select();

        $extData = [];
        $extData['units_name'] = $units['name'] ?? '';
        if(!empty($sealTasks)){
            foreach($sealTasks as $task){
                $taskSeal = Db::name('seal')->where(['id' => $task['seal_id']])->find();
                $sealAdmins = explode(',', $taskSeal['seal_admin_user']);
                if($task['stepname'] == '所在单位审核' && in_array($task['receiveid'], $sealAdmins)){
                    $extData['units_seal_url'] = $taskSeal['seal_url'];
                    $extData['units_seal_date'] = date('Y年m月d日',strtotime($task['completedtime']));
                }else if($task['stepname'] == '申请单位主管部门审批' && in_array($task['receiveid'], $sealAdmins)){
                    $extData['apply_manage_seal_url'] = $taskSeal['seal_url'];
                    $extData['apply_manage_seal_date'] = date('Y年m月d日',strtotime($task['completedtime']));
                }else if($task['stepname'] == '公物仓资产所在单位主管部门审批' && in_array($task['receiveid'], $sealAdmins)){
                    $extData['assets_manage_seal_url'] = $taskSeal['seal_url'];
                    $extData['assets_manage_seal_date'] = date('Y年m月d日',strtotime($task['completedtime']));
                }
            }
        }

        $word = new Word();
        $word->start();
        $word->writeGuihuanContent($data, $extData);
    }

    public function downloadWord()
    {
        $ids = $this->request->request('ids');
        $instanceid = $this->request->request('instanceid');

        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $instance = $this->instance->get($instanceid);
        $admin = Admin::get($instance['originator']);
        $units = Db::name('department')
            ->alias('a')
            ->join('units b', 'b.id = a.unit_id', 'LEFT')
            ->where(['a.id' => $admin['department_id']])
            ->field('b.name')
            ->find();

        $data = Db::name('assets')
            ->where(['id' => $row['assets_id']])
            ->field('id,assets_name,unit,assets_type,price,assets_sn,quantity,net_value')
            ->find();

        $sealTasks = Db::name('flow_task')->where([
            'instanceid' => $instanceid,
            'is_hide' => 0,
            'status' => 2,
            'seal_id' => ['<>',0]
        ])->select();

        if(!empty($sealTasks)){
            $domain = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'];
            foreach($sealTasks as $task){
                $taskSeal = Db::name('seal')->where(['id' => $task['seal_id']])->find();
                $sealAdmins = explode(',', $taskSeal['seal_admin_user']);
                if($task['stepname'] == '所在单位审核' && in_array($task['receiveid'], $sealAdmins)){
                    $data['units_seal_url'] = $domain.$taskSeal['seal_url'];
                    $data['units_seal_date'] = date('Y年m月d日',strtotime($task['completedtime']));
                }else if($task['stepname'] == '申请单位主管部门审批' && in_array($task['receiveid'], $sealAdmins)){
                    $data['apply_manage_seal_url'] = $domain.$taskSeal['seal_url'];
                    $data['apply_manage_seal_date'] = date('Y年m月d日',strtotime($task['completedtime']));
                }else if($task['stepname'] == '公物仓资产所在单位主管部门审批' && in_array($task['receiveid'], $sealAdmins)){
                    $data['assets_manage_seal_url'] = $domain.$taskSeal['seal_url'];
                    $data['assets_manage_seal_date'] = date('Y年m月d日',strtotime($task['completedtime']));
                }
            }
        }

        $filename = "市级公物仓资产申请归还登记表";
        header('pragma:public');
        header('Content-type:application/vnd.ms-word;charset=utf-8;name="'.$filename.'".doc');
        header("Content-Disposition:attachment;filename=$filename.doc");

        $word = new Word();
        $word->start();
        $word->writeGuihuanContent($data, $units);
    }
}
